/* eslint-disable @typescript-eslint/ban-ts-comment */
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { mergeConfig, type UserConfig } from 'vite';
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
import UnoCSS from 'unocss/vite';
import { vitePluginForArco } from '@arco-plugins/vite-vue';
// @ts-expect-error
import replacer from '../../utils/vite-plugin-replacer.js';
import prismjsPlugin from 'vite-plugin-prismjs-plus';

const __dirname = dirname(fileURLToPath(import.meta.url));

export default function viteConfig(defaultConfig: UserConfig) {
  return mergeConfig(defaultConfig, {
    plugins: [
      UnoCSS(),
      VueI18nPlugin({
        include: join(__dirname, '../common/locales/**'),
        dropMessageCompiler: true,
      }),
      replacer([
        '/@toast-ui/editor/dist/toastui-editor.css',
      ], 'overflow-X: hidden;', 'overflow-x: hidden;'),
      vitePluginForArco({
        modifyVars: {
          'arcoblue-1': '#E8F4FF',
          'arcoblue-2': '#C5E0FE',
          'arcoblue-3': '#A3CAFD',
          'arcoblue-4': '#81B2FC',
          'arcoblue-5': '#5F98FB',
          'arcoblue-6': '#3D7CFA',
          'arcoblue-7': '#2658CF',
          'arcoblue-8': '#143AA3',
          'arcoblue-9': '#072278',
          'arcoblue-10': '#000F4D',
        },
      }),
      prismjsPlugin({
        manual: true,
        languages: [
          'markup',
          'javascript',
          'css',
          'php',
          'ruby',
          'python',
          'java',
          'c',
          'csharp',
          'cpp',
          'bash',
          'rust',
        ],
        css: true,
      }),
    ],
    css: {
      postcss: __dirname,
    },
    build: {
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          manualChunks: (id: string) => {
            const deps: Record<string, string[]> = {
              vue: ['vue', 'vue-router', 'pinia', 'vue-i18n', '@vueuse/core'],
              arco: ['@arco-design/web-vue'],
              'ark-ui': ['@ark-ui'],
              chart: ['echarts'],
              'tui-editor': ['@toast-ui/editor'],
              tinymce: ['tinymce', 'tinymce-i18n', '@tinymce/tinymce-vue'],
              'markdown-it': ['markdown-it'],
              vendors: ['lazysizes', 'mitt', 'nprogress', 'pretty-bytes', 'ts-md5', 'lodash-es', 'axios', 'date-fns'],
            };

            for (const key in deps) {
              if (deps[key].some(dep => id.includes(`/node_modules/${dep}/`))) {
                return key;
              }
            }

            const chunks: Record<string, string[]> = {
              locales: ['common/locales'],
            };

            for (const key in chunks) {
              if (chunks[key].some(chunk => id.includes(`/${chunk}/`))) {
                return key;
              }
            }
          },
        },
      },
    },
  });
}
